package com.example.hotelsystem.controller.email;

import code.CodeError;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hotelsystem.entity.User;
import com.example.hotelsystem.result.Result;
import com.example.hotelsystem.service.MailService;
import com.example.hotelsystem.service.UserService;
import com.example.hotelsystem.utils.UUIDGenrateUtil;
import com.example.hotelsystem.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hotelsystem/email")
@Api(tags = "邮件控制器")
public class EmailController {
    @Autowired
    MailService mailService;

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;
    private Long userId;

    @PostMapping(value = "/sendEmail",produces = { "application/json;charset=UTF-8" })
    @ApiOperation("注册账号-发送验证码到邮箱内")
    public Result SendEmail(String email,String imageCode,String only){
        try{
            QueryWrapper<User> emailQuery = new QueryWrapper<>();
            emailQuery.eq("email",email);
            emailQuery.eq("is_delete",0);
            User checkEmail = userService.getOne(emailQuery);
            if(checkEmail!=null){
                return Result.error(CodeError.USER_EMAIL_ALREADY,"该电子邮箱已被使用");
            }

            if(redisTemplate.opsForValue().get(only+"code").toString()==null){
                return Result.error(CodeError.GET_CODE_AGAIN,"请重新获取验证码");
            }
            if(!redisTemplate.opsForValue().get(only+"code").toString().equalsIgnoreCase(imageCode)){
                return Result.error(CodeError.GET_CODE_AGAIN,"验证码错误");
            }
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("email",email);
//            User user = userService.getOne(queryWrapper);
//            if(user != null){
//                return Result.error(CodeError.EMAIL_ALREADY_EXISTS,"该邮箱已被注册使用");
//            }
            Object object = redisTemplate.opsForValue().get("email-"+email);
            if(object==null){
                String code = UUIDGenrateUtil.generateShortUuid();
                redisTemplate.opsForValue().set("email-"+email,code, 3,TimeUnit.MINUTES);
                String subject = "来自ILOVEHOTEL酒店的验证邮件";
                String context = "<div><h1>欢迎使用ILOVEHOTEL酒店</h1></div>" +
                        "<div>您的验证码为:"+code+"<div>"+
                        "<div>验证码有效时间为3分钟<div>"+
                        "<div>请不要轻易告诉别人，若存在疑问，请咨询0760-888888888<div>";
                mailService.sendHtmlMail(email,subject,context);
                return Result.success("邮件发送成功,请注意查看邮箱");
            }else{
                return Result.error(CodeError.ENMAIL_HASEBENN_SEND,"邮件已经发送，请尽快验证");
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }


    @PostMapping(value = "/checkCode",produces = { "application/json;charset=UTF-8" })
    @ApiOperation("验证验证码code")
    public Result CheckCode(String email,String code){
        try {
            Object object = redisTemplate.opsForValue().get("email-"+email);
            if(object != null){
                if(object.toString().equalsIgnoreCase(code)){
                    redisTemplate.delete("email-"+email);
                    return Result.success("验证码正确，验证成功");
                }else{
                    return Result.error(CodeError.EMAIL_CODE_ERROR,"验证码错误，请重新输入");
                }
            }else{
                return Result.error(CodeError.ENMAIL_CODE_GET_ERROR,"请先获取验证码");
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }


    @PostMapping(value = "/sendPassworEmail",produces = { "application/json;charset=UTF-8" })
    @ApiOperation("重置密码-发送验证码到邮箱内")
    public Result sendPassworEmail(String email, String imageCode,String only){
       try{
           QueryWrapper<User> emailQuery = new QueryWrapper<>();
           emailQuery.eq("email",email);
           emailQuery.eq("is_delete",0);
           User checkEmail = userService.getOne(emailQuery);
           if(checkEmail==null){
                   return Result.error(CodeError.USER_EMAIL_NO_REGIS,"该电子邮箱还未注册账号");
           }

//           HttpServletRequest request =
//                   ((ServletRequestAttributes) RequestContextHolder.
//                           getRequestAttributes()).getRequest();
//           HttpSession session=request.getSession();//创建session对象
               if(redisTemplate.opsForValue().get(only+"code").toString()==null){
                   return Result.error(CodeError.GET_CODE_AGAIN,"请重新获取验证码");
               }
               if(!redisTemplate.opsForValue().get(only+"code").toString().equalsIgnoreCase(imageCode)){
                   return Result.error(CodeError.GET_CODE_AGAIN,"验证码错误");
               }
           Object object = redisTemplate.opsForValue().get("ResetEmail-"+email);
           if(object==null){
               String code = UUIDGenrateUtil.generateShortUuid();
               QueryWrapper<User> queryWrapper = new QueryWrapper<>();
               queryWrapper.eq("email",email);
               emailQuery.eq("is_delete",0);
               User user = userService.getOne(queryWrapper);
//               session.setAttribute("ResetUserId",user.getId());
               redisTemplate.opsForValue().set("ResetEmail-"+email,code, 3,TimeUnit.MINUTES);
               String subject = "来自ILOVEHOTEL酒店的验证邮件";
               String context = "<div><h1>欢迎使用ILOVEHOTEL酒店</h1></div>" +
                       "<div>您的用户名为:"+user.getUsername()+"<div>"+
                       "<div>您的验证码为:"+code+"<div>"+
                       "<div>验证码有效时间为3分钟<div>"+
                       "<div>请不要轻易告诉别人，若存在疑问，请咨询0760-888888888<div>";
               mailService.sendHtmlMail(email,subject,context);
               return Result.success("邮件发送成功,请注意查看邮箱");
           }else{
               return Result.error(CodeError.ENMAIL_HASEBENN_SEND,"邮件已经发送，请尽快验证");
           }
       }catch (Exception e){
           return Result.error(e.getMessage());
       }
    }

    @PostMapping(value = "/checkPasswordCode",produces = { "application/json;charset=UTF-8" })
    @ApiOperation("重置密码-验证验证码code")
    public Result checkPasswordCode(String email,String code){
        try {
            Object object = redisTemplate.opsForValue().get("ResetEmail-"+email);
            if(object != null){
                if(object.equals(code)){
                    redisTemplate.delete("ResetEmail-"+email);
                    return Result.success("验证码正确，验证成功");
                }else{
                    return Result.error(CodeError.EMAIL_CODE_ERROR,"验证码错误，请重新输入");
                }
            }else{
                return Result.error(CodeError.ENMAIL_CODE_GET_ERROR,"请先获取验证码");
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/resetPassword")
    @ApiOperation("重置密码")
    public Result resetPassword(String password){
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.
                        getRequestAttributes()).getRequest();
        HttpSession session=request.getSession();//创建session对象
        Long userId= (Long) session.getAttribute("ResetUserId");
        User user = userService.getById(userId);
        user.setPassword(password);
        boolean isReset = userService.updateById(user);
        if(isReset){
            return Result.success("密码重置成功");
        }
        return Result.error(CodeError.PASSWORD_RESET_FAIL,"密码重置失败");
    }

    @PostMapping("/sendNewEmail")
    @ApiOperation("发送邮件到新邮箱")
    public Result sendEmailForNone(String email){
        try {
            String code = UUIDGenrateUtil.generateShortUuid();
            redisTemplate.opsForValue().set("newEmail-"+email,code, 3,TimeUnit.MINUTES);
            String subject = "来自ILOVEHOTEL酒店的验证邮件";
            String context = "<div><h1>欢迎使用ILOVEHOTEL酒店</h1></div>" +
                    "<div>这是一封更换邮箱的邮件<div>"+
                    "<div>您的验证码为:"+code+"<div>"+
                    "<div>验证码有效时间为3分钟<div>"+
                    "<div>请不要轻易告诉别人，若存在疑问，请咨询0760-888888888<div>";
            mailService.sendHtmlMail(email,subject,context);
            return Result.success("邮件发送成功,请注意查看邮箱");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/checkNewEmail")
    @ApiOperation("新邮箱验证码检测")
    public Result checkNewEmail(String email,String code){
        try {
            Object object = redisTemplate.opsForValue().get("newEmail-"+email);
            if(object != null){
                if(object.equals(code)){
                    redisTemplate.delete("newEmail-"+email);
                    User current = UserUtil.getUser();
                    if(current==null){
                        return Result.error("系统获取不到当前用户信息，请重新登陆或联系管理员");
                    }
                    User user = userService.getById(current.getId());
                    user.setEmail(email);
                    userService.updateById(user);
                    return Result.success("验证码正确，验证成功");
                }else{
                    return Result.error(CodeError.EMAIL_CODE_ERROR,"验证码错误，请重新输入");
                }
            }else{
                return Result.error(CodeError.ENMAIL_CODE_GET_ERROR,"请先获取验证码");
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

}
